package edu.whut.mall.admin.service.impl;


import edu.whut.mall.admin.mapper.SysUserRoleCustomMapper;
import edu.whut.mall.admin.service.ISysUserRoleService;
import edu.whut.mall.mapper.SysRoleMapper;
import edu.whut.mall.mapper.SysUserRoleMapper;
import edu.whut.mall.model.SysRole;
import edu.whut.mall.model.SysUserRole;
import edu.whut.mall.model.SysUserRoleExample;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @program: footbook
 * @description: 用户角色实现类
 * @author: Wayne
 * @create: 2020-03-17 17:09
 **/
@Service
@RequiredArgsConstructor
public class SysUserRoleServiceImpl implements ISysUserRoleService {

    private final SysUserRoleMapper sysUserRoleMapper;

    private final SysRoleMapper sysRoleMapper;
    private final SysUserRoleCustomMapper sysUserRoleCustomMapper;



    @Override
    public Integer assignRole2User(Long userId, String roleIdString) {
        clearRole2User(userId);
        String[] roleIdStringArr = roleIdString.split(",");
        long[] roleIds = Arrays.stream(roleIdStringArr).mapToLong(Long::parseLong).toArray();
        List<SysUserRole> sysUserRoleList = new ArrayList<>(roleIds.length);
        Arrays.stream(roleIds).forEach(roleId ->{
            SysUserRole sysUserRole=new SysUserRole();
            sysUserRole.setUserId(userId);
            sysUserRole.setRoleId(roleId);
            sysUserRoleList.add(sysUserRole);
        });
        return sysUserRoleCustomMapper.batchInsert(sysUserRoleList);
    }

    @Override
    public List<SysRole> listRolesByUserId(Long userId) {
       return sysRoleMapper.listRoleByUserId(userId);
    }

    /**
     * 分配之前先清空角色
     * @param userId
     */
    private void clearRole2User(Long userId){
        SysUserRoleExample example = new SysUserRoleExample();
        example.createCriteria().andUserIdEqualTo(userId);
        sysUserRoleMapper.deleteByExample(example);
    }
}
